package my.music.controller;

import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import my.music.common.result.Result;
import my.music.common.result.ResultEnum;
import my.music.common.result.ResultModel;
import my.music.dao.SheetDetailsMapper;
import my.music.dao.SheetInfoMapper;
import my.music.pojo.SheetDetails;
import my.music.pojo.SheetInfo;
import my.music.validator.Create;
import my.music.validator.Update;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import javax.validation.groups.Default;
import javax.websocket.server.PathParam;
import java.math.BigInteger;
import java.util.List;

/**
 * 歌单
 */
@RestController
@RequestMapping("sheet")
public class SheetController {
    @Resource
    private SheetInfoMapper sheetInfoMapper;
    @Resource
    private SheetDetailsMapper sheetDetailsMapper;

    /**
     * 创建歌单信息
     * @param sheetInfo
     * @return
     */
    @PostMapping("api/add/info")
    public Result<SheetInfo> addSheetInfo(@Validated({Default.class, Create.class}) SheetInfo sheetInfo){
        // 获取用户id
        long loginId = StpUtil.getLoginIdAsLong();
        sheetInfo.setUserId(BigInteger.valueOf(loginId));

        int insert = sheetInfoMapper.insert(sheetInfo);
        if (insert > 0){
            return ResultModel.success(sheetInfo);
        }
        return ResultModel.error(ResultEnum.SYSTEM_RUN_ERROR);
    }

    /**
     * 分页获取我的歌单
     * @param current 页码
     * @param size 长度
     * @return
     */
    @GetMapping("api/list/{current}")
    public Result<List<SheetInfo>> listMySheetInfoPage(@PathVariable("current") Long current, @PathParam("size") Long size){
        // 获取用户id
        Object loginId = StpUtil.getLoginId();

        QueryWrapper qw = new QueryWrapper<>()
                .eq("user_id", loginId)
                .eq("is_deleted", false);
        Page page = new Page();
        page.setCurrent(current);
        if (size != null) page.setSize(size);
        page = sheetInfoMapper.selectPage(page, qw);

        return ResultModel.success(page);
    }

    /**
     * 分页获取公开的歌单
     * @param current 页码
     * @param size 长度（默认10）
     * @param userId 用户id
     * @return
     */
    @GetMapping("list/{current}")
    public Result<List<SheetInfo>> listOpenSheetInfoPage(@PathVariable("current") Long current, @PathParam("size") Long size, @PathParam("userId") Integer userId){
        QueryWrapper qw = new QueryWrapper<>()
                .eq("is_open", true)
                .eq("is_deleted", false)
                .eq(userId != null, "user_id", userId);
        Page page = new Page();
        page.setCurrent(current);
        if (size != null) page.setSize(size);
        page = sheetInfoMapper.selectPage(page, qw);

        return ResultModel.success(page.getRecords());
    }

    /**
     * 修改我的歌单信息
     * @param sheetInfo
     * @return
     */
    @PostMapping("api/update")
    public Result updateSheetInfo(@Validated({Default.class, Update.class}) SheetInfo sheetInfo){
        // 获取用户id
        long loginId = StpUtil.getLoginIdAsLong();
        sheetInfo.setUserId(BigInteger.valueOf(loginId));

        int i = sheetInfoMapper.updateById(sheetInfo);
        if (i > 0){
            return ResultModel.success();
        }
        return ResultModel.error(ResultEnum.SYSTEM_RUN_ERROR);
    }

    /**
     * 判断歌单
     * @param userId 用户id
     * @param SheetId 歌单id
     * @return
     */
    private boolean isMySongSheet(Object userId, BigInteger SheetId){
        QueryWrapper qw = new QueryWrapper<>()
                .select("id")
                .eq("id", SheetId)
                .eq("user_id", userId);
        SheetInfo sheetInfo = sheetInfoMapper.selectOne(qw);
        if (sheetInfo == null){
            return false;
        }
        return true;
    }

    /**
     * 添加歌曲到歌单
     * @param sheetDetails
     * @return
     */
    @PostMapping("api/add/details")
    public Result addSheetDetails(@Valid SheetDetails sheetDetails){
        // 获取用户id
        Object loginId = StpUtil.getLoginId();

        // 验证
        boolean mySongSheet = isMySongSheet(loginId, sheetDetails.getSheetId());
        if (!mySongSheet){
            return ResultModel.error(ResultEnum.USER_HANDLE_EXCEPTION);
        }

        int insert = sheetDetailsMapper.insert(sheetDetails);
        if (insert > 0){
            return ResultModel.success();
        }
        return ResultModel.error(ResultEnum.SYSTEM_RUN_ERROR);
    }

    /**
     * 删除歌单内的歌曲
     * @param id 详情id|1
     * @return
     */
    @GetMapping("api/delete/details/{id}")
    public Result deleteSheetDetails(@PathVariable("id") BigInteger id){
        // 获取用户id
        Object loginId = StpUtil.getLoginId();

        // 获取详情信息
        SheetDetails sheetDetails = sheetDetailsMapper.selectById(id);

        // 验证
        boolean mySongSheet = isMySongSheet(loginId, sheetDetails.getSheetId());
        if (!mySongSheet){
            return ResultModel.error(ResultEnum.USER_HANDLE_EXCEPTION);
        }

        int i = sheetDetailsMapper.deleteById(id);
        if (i > 0){
            return ResultModel.success();
        }
        return ResultModel.error(ResultEnum.SYSTEM_RUN_ERROR);
    }


}
